package com.china08.yxyapi.api.manage.edu.platform.continuedu.lesson;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.continuedu.YxyContinueduLesson;
import com.china08.yxyapi.entity.db.continuedu.YxyContinueduLessonItem;
import com.china08.yxyapi.entity.db.continuedu.YxyContinueduLessonsVideo;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.repository.db.continuedu.YxyContinueduLessonItemRepository;
import com.china08.yxyapi.repository.db.continuedu.YxyContinueduLessonRepository;
import com.china08.yxyapi.repository.db.continuedu.YxyContinueduLessonsVideoRepository;

import io.swagger.annotations.ApiOperation;

@CrossOrigin
@RestController
public class YxyContinueduLessonDelItemController extends YxyApiBaseController {

    @Autowired
    YxyContinueduLessonItemRepository itemRepository;

    @Autowired
    YxyContinueduLessonsVideoRepository videoRepository;

    @Autowired
    YxyContinueduLessonRepository lessonRepository;

    /**
     * @param request
     * @param response
     * @param reqModel
     */
    @ApiOperation(value = "")
    @RequestMapping(value = "/api_yw/manage/edu/platform/continuedu/lesson/del/item", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void precess(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) {
        String id = reqModel.id;
        String lessonId = "";
        YxyContinueduLessonItem item = itemRepository.findById(id);
        if (item != null) {
            lessonId = item.getLessonId();
            itemRepository.delete(item);
        }

        // 从新计算总课时
        Integer duration = 0;
        List<YxyContinueduLessonItem> itemList = itemRepository.findByLessonId(lessonId);
        for (YxyContinueduLessonItem item2 : itemList) {
            String videoId = item2.getVideoId();
            YxyContinueduLessonsVideo video = videoRepository.findById(videoId);
            if (video != null) {
                duration = duration + video.getDuration();
            }
        }
        YxyContinueduLesson lesson = lessonRepository.findById(lessonId);
        if (lesson != null) {
            lesson.setDuration(duration);
            lessonRepository.saveAndFlush(lesson);
        }
    }

    public static class ReqModel extends YxyApiReqModel {
        public String id;
    }
}
